import re
import requests
import json
from requests_toolbelt import MultipartEncoder
from frame_work.type_file import (
    Source,
    TypeSource,
    RewardOrderType
)
from frame_work.release_util import low_release
from frame_work.logger import Logger
from frame_work.util import (
    get_sql_info,
    change_user_account_status,
    get_binded_shop_list,
    bind_shop,
    get_seller_level,
    get_order_url,
    assert_result_dict
)
from frame_work.login import PcLogin
from frame_work import menu_list
from workspace.shikee.chuji.pay import PayQuantity
from frame_work.setting import *
from frame_work.yaml_file import YAML


logger = Logger(__name__).get_logger()


class Activity(object):

    def __init__(self, uname):
        self.uname = uname
        # self.logger = Logger(logger="release").get_logger()
        self.session = self.get_session()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_session(self):
        """
        :return:返回登录session
        """
        login = PcLogin(self.uname)
        login.pc_login()
        return login.get_session()

    def get_html(self):
        """
        请求一个页面，在响应中获取比如：token，shopId等
        :return: html
        """
        url = self.yaml.get_data("token").get('url')
        html = self.session.get(url).text
        return html

    def get_token(self):
        """
        从html中通过正则表达式获取token
        :return:token
        """
        complex_value = 'name="token" value="(.*?)"'
        html = self.get_html()
        token = re.findall(complex_value, html)
        try:
            token = token[0]
            logger.debug('获取token值 => %s ...' % token)
        except (IndexError, KeyError) as e:
            logger.debug("获取token出错")
            return False
        else:
            return token

    @staticmethod
    def get_brand_category():
        """
        返回品牌活动的id和类别id
        :return:
        """
        statement = """SELECT
                        bc.id AS bcid,
                        bc. NAME AS bcname,
                        b.id AS bid,
                        b. NAME AS bname
                    FROM
                        sk_brand_category bc,
                        sk_brand b
                    WHERE
                        bc.id = b.cate_id
                    AND b.`status` = 1
                        """
        params = ()
        value = get_sql_info(statement, params, meta={
            "info": "查询品牌活动的id和类别id"
        })
        try:
            bcid = value[0].get("bcid")
            bid = value[0].get("bid")
            logger.debug('获取品牌id => %s %s...' % (bcid, bid))
        except Exception as e:
            logger.error('没有可用的品牌id，请自行后台添加')
            return False
        else:
            return bcid, bid

    # @staticmethod
    # def get_dic_value(dic1,value):
    #     """
    #     dict中，通过value值反向获取key
    #     :param dic1:
    #     :param value:
    #     :return: key
    #     """
    #     key = list(dic1.keys())[list(dic1.values()).index(value)]
    #     return key

    @staticmethod
    def get_title(type, source):
        """
        通过活动类型和来源的拼接，返回对应的title
        :param type:活动类型
        :param source:来源
        :return:title
        """
        # source_key = Activity.get_dic_value(sourcev,value)
        if source == '淘宝':  # 商品来源为淘宝
            title = type + '_淘宝' + '_刘'
        elif source == '天猫':  # 商品来源为天猫
            title = type + '_天猫' + '_刘'
        elif source == '京东':  # 商品来源为京东
            title = type + '_京东' + '_刘'
        elif source == '拼多多':  # 商品来源为拼多多
            title = type + '_拼多多' + '_刘'
        elif source == '食遍天':  # 商品来源为食遍天
            title = type + '_食遍天' + '_刘'
        elif source == '试用联盟':  # 商品来源为试用联盟
            title = type + '_试用联盟' + '_刘'
        elif source == '微店':  # 商品来源为微店
            title = type + '_微店' + '_刘'
        elif source == '阿里巴巴':  # 商品来源为阿里巴巴
            title = type + '_阿里巴巴' + '_刘'
        elif source == '划算自营':  # 商品来源为划算自营
            title = type + '_划算自营' + '_刘'
        elif source == '淘宝特价版':  # 商品来源为划算自营
            title = type + '_淘宝特价' + '_刘'
        elif source == '抖音':  # 商品来源为划算自营
            title = type + '_抖音' + '_刘'
        else:  # 商品来源为其它
            title = type + '_其他' + '_刘'
        logger.debug('根据来源获取title值 => %s ...' % title)
        return title

    @staticmethod
    def get_image(title):
        """
        通过title来判断/image下取哪个image图片，主要用于get_pic函数中用于post
        :param title:
        :return:
        """
        title = title[:-2]
        for image in os.listdir(image_Path):
            if title + '.jpg' == image:
                return image

    def get_pic(self, num, title):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取响应值类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :param title:活动类型与来源的拼接
        :return:pic_addr
        """
        shikee_cookies = self.session.cookies.get(
            'shikee')  # 获取用户cookies中的shikee部分
        yaml_data = self.yaml.get_data("tmp_pic_address")
        yaml_data.get('data').update({
            'name': Activity.get_image(title),  # num:发布活动页面有多个上传图片地方,用于区别
            'Filedata': ('filename', open(os.path.join(image_Path, Activity.get_image(title)), 'rb'), 'image/jpg')
        })
        url = yaml_data.get('url') + '/' + str(num) + \
            '?swf_upload_cookie=' + shikee_cookies
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = requests.post(url, data=m,
                          headers={'Content-Type': m.content_type})
        return r.text

    @staticmethod
    def get_source(sources):
        """
        获取活动来源
        :param sources:活动来源
        :return:source
        """
        # sources = type_source.get(type)
        # sources = TypeSource.type1.name
        for index, source in enumerate(sources, start=1):
            print("%s : %s" % (index, source))
        try:
            choise_source = int(input("请选择活动来源选项:\t\n---->  "))
        except BaseException as e:
            logger.error('输入选项错误，请选择对应序号')
        else:
            if choise_source > len(sources):
                logger.error('超出选项范围')
                return False
            else:
                source = sources[int(choise_source) - 1]
                return source

    def release_basic(self, *args, **kwargs):
        """
        发布封装
        :param args:
        :param kwargs:
        :return:
        """
        source = kwargs.get("source")
        cn_type = kwargs.get("cn_type")
        try_type = kwargs.get("try_type")
        order_url = kwargs.get("order_url")
        value = get_seller_level(self.uname)
        level = value[0].get("level")
        if level in [11, 12]:
            logger.info("王者/星耀vip不能发布初级试用")
            return
        shop_id = ''
        if level != 1:
            if try_type == 22:
                logger.info("vip商家不支持发布特价版活动类型活动")
                return
            value = get_binded_shop_list(self.uname, source)
            if not value:
                bind_shop(source, self.uname)
                value = get_binded_shop_list(self.uname, source)
            shop_id = value[0].get("sid")
        if not order_url:
            order_url = get_order_url(source)
        # title = self.get_title('普通活动',source_value)
        if args:
            title = Activity.get_title(cn_type + "_" + args[0], source)
        else:
            title = Activity.get_title(cn_type, source)
        title_pic = json.loads(self.get_pic(1, title)).get('data')
        result_pic = json.loads(self.get_pic(2, title)).get('data')
        wd_pic = json.loads(self.get_pic(2, title)).get('data')
        qr_pic = json.loads(self.get_pic(3, title)).get('data')
        pingou_img = json.loads(self.get_pic(3, title)).get('data')
        url, post_data, header = low_release(
            source=source, token=self.get_token(), trysType=try_type,
            trySource=Source[source].value, shopId=shop_id, shop_name=source + "的店铺",
            Title=title, url_order=order_url, order_type=kwargs.get(
                "order_type"),
            title_pic=title_pic, result_pic=result_pic, wd_pic=wd_pic, qr_pic=qr_pic,
            pingou_img=pingou_img, bcid=kwargs.get("bcid"), bid=kwargs.get("bid"),
            shop_wangwang_name=kwargs.get("shop_wangwang_name")
        )
        logger.debug('开始发布' + cn_type)
        response = self.session.post(url, data=post_data, headers=header).text
        cn_level = '单期商家' if level == 1 else 'vip商家'
        status = assert_result_dict(
            response, cn_level + self.uname + '发布' + cn_type)
        self.pay(status, response)

    def release_activity_general(self, source):
        """
        发布普通活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='普通活动', try_type=1)

    def release_activity_answer(self, source):
        """
        发布答案试用活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='答案试用', try_type=4)

    def release_activity_search_order(self, source):
        """
        发布PC搜索下单活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='搜索下单', try_type=2)

    def release_activity_st_order(self, source):
        """
        发布手淘下单活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='手淘下单', try_type=6)

    def release_activity_command_order(self, source):
        """
        发布口令下单活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='口令下单', try_type=7)

    def release_activity_command_search(self, source):
        """
        发布口令搜索活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='口令搜索', try_type=13)

    def release_activity_qr_search(self, source):
        """
        发布扫码搜索活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='扫码搜索', try_type=15)

    def release_activity_st_search(self, source):
        """
        发布手淘搜索活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='手淘搜索', try_type=8)

    def release_activity_pc_order(self, source):
        """
        发布PC端付费活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='PC端付费试用', try_type=10)

    def release_activity_app_order(self, source):
        """
        发布APP端付费活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='APP端付费试用', try_type=11)

    def release_activity_reward(self, order_type, source):
        """
        发布任务试用活动类型
        :param source: 活动来源
        :return:
        """
        if order_type == 1:
            self.release_basic(
                '关键词下单',
                source=source,
                cn_type='任务试用',
                try_type=14,
                order_type=order_type)
        else:
            self.release_basic(
                '口令搜索',
                source=source,
                cn_type='任务试用',
                try_type=14,
                order_type=order_type)

    def release_activity_st_package(self, source):
        """
        发布手淘套餐活动类型
        :param source: 活动来源
        :return:
        """
        shop_wangwang_name = source + "的旺旺店铺"
        order_url = get_order_url(source, 2)
        self.release_basic(
            source=source,
            cn_type='手淘套餐',
            try_type=19,
            order_url=order_url,
            shop_wangwang_name=shop_wangwang_name)

    def release_activity_app(self, source):
        """
        废弃
        发布app抢试用活动类型
        :param source: 活动来源
        :return:
        """
        # self.release_basic(source=source,cn_type='APP活动',try_type=5)
        pass

    def release_activity_multimode(self, source):
        """
        发布多模式下单试用活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='多模式下单', try_type=17)

    def release_activity_brand(self, source):
        """
        发布品牌活动类型
        :param source: 活动来源
        :return:
        """
        ids = Activity.get_brand_category()
        bcid = ids[0]
        bid = ids[1]
        self.release_basic(
            source=source,
            cn_type='品牌活动',
            try_type=20,
            bcid=bcid,
            bid=bid)

    def release_activity_pingou(self, source):
        """
        发布拼购活动类型
        :param source: 活动来源
        :return:
        """
        order_url = get_order_url(source, 2)
        self.release_basic(
            source=source,
            cn_type='拼购活动',
            try_type=21,
            order_url=order_url)

    def release_activity_free_guaranty(self, source):
        """
        发布试用营销试用活动类型
        :param source: 活动来源
        :return:
        """
        value = get_seller_level(self.uname)
        level = value[0].get("level")
        # shop_id = ''
        if level != 1:
            # shop_id = self.get_shopId(source)
            value = get_binded_shop_list(self.uname, '其他')
            if not value:
                bind_shop('其他', self.uname)
        title = Activity.get_title('试用营销', source)
        title_pic = json.loads(self.get_pic(1, title)).get('data')
        url, post_data, header = low_release(
            token=self.get_token(), trysType=16,
            trySource=Source[source].value, shop_name=source + "的店铺",
            Title=title, url_order=get_order_url(source), title_pic=title_pic
        )
        logger.debug('开始发布试用营销试用活动')
        response = self.session.post(url, data=post_data, headers=header).text
        status = assert_result_dict(response, self.uname + '发布试用营销')
        self.pay(status, response)

    def release_activity_scp(self, source):
        """
        发布试潮品试用活动类型
        :param source: 活动来源
        :return:
        """
        value = get_seller_level(self.uname)
        level = value[0].get("level")
        if level != 1:
            value = get_binded_shop_list(self.uname, '其他')
            if not value:
                bind_shop('其他', self.uname)
        title = '试潮品_刘'
        title_pic = json.loads(self.get_pic(1, title)).get('data')
        url, post_data, header = low_release(
            token=self.get_token(), trysType=9,
            Title=title, url_order=get_order_url(source),
            title_pic=title_pic
        )
        logger.debug('开始发布试潮品试用活动')
        response = self.session.post(url, data=post_data, headers=header).text
        status = assert_result_dict(response, self.uname + '发布试潮品')
        self.pay(status, response)

    def release_activity_tj(self, source):
        """
        发布淘宝特价版试用活动类型
        :param source: 活动来源
        :return:
        """
        self.release_basic(source=source, cn_type='淘宝特价版', try_type=22)

    def pay(self, status, response):
        if status:
            tid = json.loads(response).get("data").split('/')[-1]
            # tid = 70000549
            logger.info("该活动tid为：%s 即将执行支付活动担保金操作...  请稍等...." % tid)
            # logger.info("即将执行支付活动担保金操作...  请稍等....")
            pay = PayQuantity(self.session)
            # pay.test_pay_quantity(tid)
            pay.pay_quantity(tid)

def main():
    while True:
        # 选择功能菜单
        menu_list.release_menu()
        # 选择
        choise = input("请选择活动类型: ")
        if choise in ('q', 'Q'):
            break
        seller_uname = input(u'请输入商家用户名: ')
        status = change_user_account_status(seller_uname)
        if not status:
            break
        activity = Activity(seller_uname)
        if choise == '1':
            source = activity.get_source(TypeSource.TYPE_ORDINARY.value)
            if source:
                activity.release_activity_general(source)
        elif choise == '2':
            source = activity.get_source(TypeSource.TYPE_ANSWER.value)
            if source:
                activity.release_activity_answer(source)
        elif choise == '3':
            source = activity.get_source(TypeSource.TYPE_SEARCH.value)
            if source:
                activity.release_activity_search_order(source)
        elif choise == '4':
            source = activity.get_source(TypeSource.TYPE_APP_ORDER.value)
            if source:
                activity.release_activity_st_order(source)
        elif choise == '5':
            source = activity.get_source(TypeSource.TYPE_APP_TAO.value)
            if source:
                activity.release_activity_command_order(source)
        elif choise == '6':
            source = activity.get_source(
                TypeSource.TYPE_APP_ORDER_SEARCH.value)
            if source:
                activity.release_activity_command_search(source)
        elif choise == '7':
            source = activity.get_source(TypeSource.TYPE_APP_SCAN_SEARCH.value)
            if source:
                activity.release_activity_qr_search(source)
        elif choise == '8':
            source = activity.get_source(
                TypeSource.TYPE_MOBILE_TAO_SEARCH.value)
            if source:
                activity.release_activity_st_search(source)
        elif choise == '9':
            source = activity.get_source(TypeSource.TYPE_APP_PACKAGE.value)
            if source:
                activity.release_activity_st_package(source)
        elif choise == '10':
            source = activity.get_source(TypeSource.TYPE_PAY_WEB.value)
            if source:
                activity.release_activity_pc_order(source)
        elif choise == '11':
            source = activity.get_source(TypeSource.TYPE_PAY_APP.value)
            if source:
                activity.release_activity_app_order(source)
        elif choise == '12':
            print(u'-------------------选择------------------------------')
            print('\t\t1：关键词搜索下单\t2：口令搜索下单\t')
            print('-----------------------------------------------------')
            choise_order_type = input("请选择活动下单方式选项:  ")
            if choise_order_type == '1':
                order_type = RewardOrderType.KEYWORD_ORDER_TYPE.value
                sources = TypeSource.TYPE_REWARD.value.get(
                    'KEYWORD_ORDER_TYPE')
                for index, source in enumerate(sources, start=1):
                    print("%s : %s" % (index, source))
                choise_source = input("请选择活动来源选项:  ")
                source = sources[int(choise_source) - 1]
                activity.release_activity_reward(order_type, source)
            elif choise_order_type == '2':
                order_type = RewardOrderType.COMMAND_SEARCH_ORDER_TYPE.value
                sources = TypeSource.TYPE_REWARD.value.get(
                    'COMMAND_SEARCH_ORDER_TYPE')
                for index, source in enumerate(sources, start=1):
                    print("%s : %s" % (index, source))
                choise_source = input("请选择活动来源选项:  ")
                source = sources[int(choise_source) - 1]
                activity.release_activity_reward(order_type, source)
        elif choise == '13':
            source = activity.get_source(TypeSource.TYPE_MULTIMODE.value)
            if source:
                activity.release_activity_multimode(source)
        elif choise == '14':
            source = activity.get_source(
                TypeSource.TYPE_FREE_PAY_GUARANTY.value)
            if source:
                activity.release_activity_free_guaranty(source)
        elif choise == '15':
            pass
            # activity.release_activity_scp("潮品试用")
        elif choise == '16':
            source = activity.get_source(TypeSource.TYPE_BRAND.value)
            if source:
                activity.release_activity_brand(source)
        elif choise == '17':
            source = activity.get_source(TypeSource.TYPE_PINGOU.value)
            if source:
                activity.release_activity_pingou(source)
        elif choise == '18':
            source = activity.get_source(TypeSource.TYPE_TEJIA.value)
            if source:
                activity.release_activity_tj(source)
        else:
            logger.info("没有对应的输入选项,请按选项输入...")
            break


if __name__ == "__main__":
    # main()
    s = Activity(uname='user0637')
    s.pay(1,1)